package com.gdk.ksoft.ui.reporters;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.ConstantData;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.assembly.dbhelper.FfindGoodsDbHelper;
import com.gdk.ksoft.data.entry.datas.BaseResultModel;
import com.gdk.ksoft.data.entry.tables.CxqhGoodsTable;
import com.gdk.ksoft.data.entry.tables.CxqhTable;
import com.gdk.ksoft.ui.works.FindbyBrandActivity;
import com.gdk.ksoft.assembly.dialog.MessageBox;
import com.gdk.ksoft.assembly.utils.extensions.ControlUtils;
import com.gdk.ksoft.assembly.utils.extensions.MD5Utils;
import com.gdk.ksoft.assembly.utils.system.FileUtils;
import com.gdk.ksoft.assembly.utils.system.NetworkUtils;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 车销请货单商品查找页面
 */
public class CxqhFindActivity extends Activity implements View.OnTouchListener{

    public static final int REQ_CODE_GOODS_BRAND = 0X0001;//请求商品品牌的查询

    @ViewInject(R.id.pcxqhFind_etGoodsSearch)private EditText etKeyword;//关键字
    @ViewInject(R.id.pcxqhFind_svGoodsContainer)private ScrollView svGoodsContainer;//滚动容器
    @ViewInject(R.id.pcxqhFind_llGoodsContainer)private LinearLayout llGoodsContainer;//车销清货商品容器
    @ViewInject(R.id.pcxqhFind_txtJs)private TextView txtJs;//商品统计件数
    @ViewInject(R.id.pcxqhFind_txtSs)private TextView txtSs;//车销统计散数
    @ViewInject(R.id.pcxqhFind_imgRefresh)private ImageView imgRefresh;//刷新按钮

    private DbUtils dbUtils;//数据操作对象
    private static final int PAGE_COUNT = 20;//每页数量20
    private int currentPageIndex = 0,pageCount = 0;//当前页码及页码总数
    private List<HashMap<String,Object>> tmpGoodsList = new ArrayList<>();//临时分页数据集合

    public static final int MSG_REFRESH_LISTVIEW = 0x0001;//刷新列表

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
                case MSG_REFRESH_LISTVIEW://刷新列表
                    List<HashMap<String,Object>> tmpList = (List<HashMap<String,Object>>)msg.obj;
                    if(tmpList == null ||tmpList.size()<=0) return;
                    tmpGoodsList.addAll(tmpList);//添加到计量值
                    int dataLen = tmpGoodsList.size();
                    currentPageIndex = 0;//设置当前页码索引0
                    pageCount = dataLen%PAGE_COUNT == 0?dataLen/PAGE_COUNT:dataLen/PAGE_COUNT+1;
                    List<HashMap<String,Object>> pageList = null;
                    if(pageCount == 1){
                        pageList = tmpList.subList(0,dataLen%PAGE_COUNT == 0?PAGE_COUNT:dataLen%PAGE_COUNT);
                    }else{
                        pageList = tmpList.subList(0,PAGE_COUNT);
                    }
                    initGoodsList(pageList);//新增列表数据
                    break;
                
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cxqh_find);
        ViewUtils.inject(this);
        dbUtils = SQLiteUtils.getInstance(this).getDbUtils();
        createCxqhTable();//如果不存在车销请货表，则创建车销请货表
        svGoodsContainer.setOnTouchListener(this);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                showDownloadKcDialog();//显示提示下载库存的提示框
            }
        },200);
    }

    /**
     * 滚动视图触屏事件
     * @param view
     * @param motionEvent
     * @return
     */
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
                int scrollY=view.getScrollY();
                int height=view.getHeight();
                int scrollViewMeasuredHeight=svGoodsContainer.getChildAt(0).getMeasuredHeight();
                if(scrollY==0){
                    System.out.println("滑动到了顶端 view.getScrollY()="+scrollY);
                }
                if((scrollY+height)>=scrollViewMeasuredHeight-2){
                    currentPageIndex++;
                    if(currentPageIndex > pageCount - 1){
                        currentPageIndex = pageCount - 1;
                        return false;
                    }
                    int dataLen = tmpGoodsList.size();
                    int backPageIndex = currentPageIndex + 1;
                    List<HashMap<String,Object>> pageList = null;
                    if(currentPageIndex == pageCount - 1){
                        pageList = tmpGoodsList.subList(currentPageIndex*PAGE_COUNT,
                                dataLen%PAGE_COUNT == 0?backPageIndex*PAGE_COUNT
                                        :currentPageIndex*PAGE_COUNT + dataLen%PAGE_COUNT);
                    }else{
                        pageList = tmpGoodsList.subList(currentPageIndex*PAGE_COUNT,
                                backPageIndex*PAGE_COUNT);
                    }
                    initGoodsList(pageList);//新增列表数据
                }
                break;
            default:
                break;
        }
        return false;
    }

    /**
     * 界面组件点击事件
     * @param view
     */
    @OnClick(value={
            R.id.pcxqhFind_txtClear,R.id.pcxqhFind_txtSearch,
            R.id.pcxqhFind_txtSearchByBrand,R.id.pcxqhFind_txtSubmitGoods,
            R.id.pcxqhFind_imgRefresh
    })
    public void onViewClick(View view){
        switch(view.getId()){
            case R.id.pcxqhFind_txtClear://清空输入文字
                etKeyword.setText("");
                break;
            case R.id.pcxqhFind_txtSearch://查找商品
                String keyword = etKeyword.getText().toString();
                if(TextUtils.isEmpty(keyword)){
                    ControlUtils.showToast(this,"请输入关键字!",Gravity.CENTER,Toast.LENGTH_SHORT);
                    return;
                }
                resetAllData();//重置数据
                executeFindAllGoodsByKeyword(this,dbUtils,keyword);//
                break;
            case R.id.pcxqhFind_txtSearchByBrand://根据品牌输出
                Intent intent = new Intent(this, FindbyBrandActivity.class);
                startActivityForResult(intent,REQ_CODE_GOODS_BRAND);
                break;
            case R.id.pcxqhFind_txtSubmitGoods://保存商品
                if(llGoodsContainer.getChildCount()<=0){
                    ControlUtils.showToast(this,"当前没有可添加的商品!",Gravity.CENTER,Toast.LENGTH_SHORT);
                    return;
                }
                executeAddGoodsToListTask(this);//保存当前的商品至内存中
                break;
            case R.id.pcxqhFind_imgRefresh://刷新库存信息
                requestGoodsStockInfo(CxqhFindActivity.this,dbUtils);//下载库存数据
                break;
        }
    }

    /**
     * 显示提示下载库存的提示框
     */
    public void showDownloadKcDialog(){
        final MessageBox msgBox = new MessageBox(this);
        msgBox.setMessage("请获取当前的库存信息!");
        msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msgBox.dismiss();
                if(v.getId() == MessageBox.ID_DIALOG_BUTTON_OK){
                    requestGoodsStockInfo(CxqhFindActivity.this,dbUtils);//下载库存数据
                }
            }
        });
        msgBox.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQ_CODE_GOODS_BRAND && resultCode == Activity.RESULT_OK){//品牌数据的请求
            if(data!=null){//根据商品品牌查询商品
                resetAllData();//重置数据
                int brandId = data.getIntExtra("brandId",0);
                executeFindAllGoodsByBrandId(this,dbUtils,brandId);
            }
        }
    }

    /**
     * 创建车销请货表
     */
    public void createCxqhTable(){
        try {
            if (!dbUtils.tableIsExist(CxqhTable.class)) {
                dbUtils.createTableIfNotExist(CxqhTable.class);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 重置所有数据
     */
    public void resetAllData(){
        txtJs.setText("件数：0");
        txtSs.setText("散数：0");
        llGoodsContainer.removeAllViews();
        currentPageIndex = 0;
        pageCount = 0;
        tmpGoodsList.clear();
    }

    /**
     * 获取刷新按钮旋转动画
     * @return
     */
    public Animation getRefreshAnimation(){
        RotateAnimation animation = new RotateAnimation(360f,0f,
                RotateAnimation.RELATIVE_TO_SELF,0.5f,
                RotateAnimation.RELATIVE_TO_SELF,0.5f);
        animation.setRepeatCount(-1);
        animation.setDuration(500);
        animation.setInterpolator(new LinearInterpolator());
        return animation;
    }

    /**
     * 初始化商品列表
     */
    public void initGoodsList(List<HashMap<String,Object>> goodsList){
        if(goodsList ==null || goodsList.size()<=0) return;
        for(final HashMap<String,Object> item : goodsList){
            final View itemView = View.inflate(this,R.layout.item_tbl_cxqh_goodslst,null);
            final String kc = item.get("sp_kc").toString().split("[.]")[0];//处理库存数据
            ((TextView)itemView.findViewById(R.id.item_tbl_cxqh_goodslst_txtKc))
                    .setText(kc.equals("0")?"" : kc);
            TextView txtGoodsName = (TextView)itemView.findViewById(R.id.item_tbl_cxqh_goodslst_txtName);
            txtGoodsName.setText(item.get("sp_mc").toString());
            txtGoodsName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //显示全部商品名及库存信息
                    final MessageBox msgBox = new MessageBox(CxqhFindActivity.this);
                    String message = "名称：" + item.get("sp_mc") + "\n"
                            +"条码：" + item.get("sp_tm") + "\n"
                            +"规格：" + item.get("sp_gg") + "\n"
                            +"库存：" + (kc.equals("0") ? "无" : kc  + "件" ) + "\n";
                    msgBox.setMessage(message);
                    msgBox.txtCancel.setVisibility(View.GONE);
                    msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            msgBox.dismiss();
                        }
                    });
                    msgBox.show();
                }
            });
            final EditText etSs = (EditText)itemView.findViewById(R.id.item_tbl_cxqh_goodslst_etSs);
            etSs.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {}
                @Override
                public void afterTextChanged(Editable s) {
                    try{
                        String ssStr = ControlUtils.getNumberStringFromTextView(etSs);
                        int intSs = Integer.parseInt(ssStr);
                        item.put("ss",ssStr);//设置散数
                        itemView.setTag(item);
                        int intHsgx = Integer.parseInt(item.get("sp_hsgx").toString());
                        if(Math.abs(intSs) >= intHsgx){
                            ControlUtils.showToast(CxqhFindActivity.this,"散数大于换算关系数量："+intHsgx, Gravity.CENTER,Toast.LENGTH_SHORT);
                        }
                        makeAccount();//做商品数量统计
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
            final EditText etJs = (EditText)itemView.findViewById(R.id.item_tbl_cxqh_goodslst_etJs);
            etJs.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {}
                @Override
                public void afterTextChanged(Editable s) {
                    try{
                        String jsStr = ControlUtils.getNumberStringFromTextView(etJs);
                        int intJs = Integer.parseInt(jsStr);
                        item.put("js",intJs);//设置散数
                        itemView.setTag(item);
                        makeAccount();//做商品数量统计
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
            itemView.setTag(item);//设置数据对象
            llGoodsContainer.addView(itemView);//添加该项到视图中去
        }
    }


    /**
     * 做商品数量统计
     */
    public void makeAccount(){
        int count = llGoodsContainer.getChildCount();//子项总数量
        int js = 0,ss = 0;//件数和散数统计变量
        for(int i=0;i<count;i++){//循环处理每个子项
            View itemView  = llGoodsContainer.getChildAt(i);
            try {
                EditText etJs = (EditText) itemView.findViewById(R.id.item_tbl_cxqh_goodslst_etJs);
                EditText etSs = (EditText) itemView.findViewById(R.id.item_tbl_cxqh_goodslst_etSs);
                String JsStr = ControlUtils.getNumberStringFromTextView(etJs);
                String SsStr = ControlUtils.getNumberStringFromTextView(etSs);
                js += Integer.parseInt(JsStr);
                ss += Integer.parseInt(SsStr);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        txtJs.setText("件数："+js);
        txtSs.setText("散数："+ss);
    }


    /**
     * 枚举的错误类型
     */
    public enum GoodsArgumentError{
        NUMBER_ERROR,//数量输入错误
        NAN_ERROR,//非法字符错误
        NONE_ERROR,//无错误
        NONE_DATA//无数据
    }

    /**
     * 监测列表数据
     * @param tmpCheckList
     */
    public GoodsArgumentError checkListData(List<HashMap<String,Object>> tmpCheckList)throws Exception{
        if(tmpCheckList == null){//
            throw new Exception("Error: 参数1 tmpCheckList为NULL!");
        }
        int count = llGoodsContainer.getChildCount();//子项总数量
        if(count <= 0) {//无数据
            return GoodsArgumentError.NONE_DATA;
        }
        for(int i=0;i<count;i++){//循环处理每个子项
            View itemView  = llGoodsContainer.getChildAt(i);
            try {
                EditText etJs = (EditText) itemView.findViewById(R.id.item_tbl_cxqh_goodslst_etJs);
                EditText etSs = (EditText) itemView.findViewById(R.id.item_tbl_cxqh_goodslst_etSs);
                String JsStr = ControlUtils.getNumberStringFromTextView(etJs);
                String SsStr = ControlUtils.getNumberStringFromTextView(etSs);
                int intJs = Integer.parseInt(JsStr);
                int intSs = Integer.parseInt(SsStr);
                if (intJs == 0 && intSs == 0) continue;
                if (intJs < 0 || intSs < 0) {
                    return GoodsArgumentError.NUMBER_ERROR;
                }
                HashMap<String, Object> item = (HashMap<String, Object>) itemView.getTag();
                int hsgx = Integer.parseInt(item.get("sp_hsgx").toString());//获取换算关系
                item.put("js", intJs+intSs/hsgx);//重新计算件数
                item.put("ss", intSs%hsgx);//重新计算散数
                tmpCheckList.add(item);
            }catch(Exception e){
                e.printStackTrace();
                return GoodsArgumentError.NAN_ERROR;//非数字字符
            }
        }
        return tmpCheckList.size()>0?GoodsArgumentError.NONE_ERROR:GoodsArgumentError.NONE_DATA;
    }

    /**
     * 把列表中的商品加入集合中去
     */
    public void executeAddGoodsToListTask(final Context context){
        new AsyncTask<Void,Void,Void>(){
            private GoodsArgumentError errorState = GoodsArgumentError.NONE_DATA;
            private ProgressDialog dialog = null;
            private String errMessage = null;//错误信息
            private List<HashMap<String,Object>> goodsList = new ArrayList<HashMap<String, Object>>();
            private DbUtils dbUtils;//数据库操作对象

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dbUtils = SQLiteUtils.getInstance(context).getDbUtils();
                dialog = ProgressDialog.show(context,"","正在提交数据...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try{
                    errorState = checkListData(goodsList);
                    if(errorState == GoodsArgumentError.NONE_ERROR && goodsList!=null
                            && goodsList.size()>0){//添加商品到数据表
                        SQLiteDatabase database = dbUtils.getDatabase();
                        try {
                            database.beginTransaction();
                            for (HashMap<String, Object> item : goodsList) {
                                CxqhGoodsTable citem = new CxqhGoodsTable();
                                citem.sp_id = Integer.parseInt(item.get("sp_id").toString());
                                citem.js = Integer.parseInt(item.get("js").toString());
                                citem.ss = Integer.parseInt(item.get("ss").toString());
                                dbUtils.save(citem);
                            }
                            database.setTransactionSuccessful();
                        }catch(Exception e){
                            errMessage = e.getMessage();
                            e.printStackTrace();
                        }finally {
                            database.endTransaction();
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    errMessage = e.getMessage();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if(errMessage!=null){
                    ControlUtils.showToast(context,"操作数据失败，请检查你的数据后并重试!",Gravity.CENTER,Toast.LENGTH_SHORT);
                    return;
                }
                if(errorState == GoodsArgumentError.NAN_ERROR){
                    ControlUtils.showToast(context,"您的输入中存在非法字符，请检查您的输入后并重试!",Gravity.CENTER,Toast.LENGTH_SHORT);
                }else if(errorState == GoodsArgumentError.NONE_DATA){
                    ControlUtils.showToast(context,"当前没有任何商品可添加!",Gravity.CENTER,Toast.LENGTH_SHORT);
                }else if(errorState == GoodsArgumentError.NONE_ERROR){
                    resetAllData();//初始化列表数据
                    ControlUtils.showToast(context,"添加商品成功!",Gravity.CENTER,Toast.LENGTH_SHORT);
                }else if(errorState == GoodsArgumentError.NUMBER_ERROR){
                    ControlUtils.showToast(context,"您的输入中数量错误，请检查您的输入后并重试!",Gravity.CENTER,Toast.LENGTH_SHORT);
                }
            }
        }.execute();
    }

    /**
     * 执行按品牌查询商品的操作
     * @param context
     * @param dbUtils
     * @param brandId  品牌ID
     */
    public void executeFindAllGoodsByBrandId(final Context context,final DbUtils dbUtils,final int brandId){
        new AsyncTask<Void,Void,Void>(){

            private ProgressDialog dialog = null;
            private String errMessage = null;
            private List<HashMap<String,Object>> goodsList = null;//商品集合

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在加载中...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try{
                    goodsList = FfindGoodsDbHelper.findAllCxqhGoodsByBrandId(dbUtils,brandId);
                }catch (Exception e){
                    e.printStackTrace();
                    errMessage = e.getMessage();
                    System.out.println("----->按商品品牌查询出错："+errMessage);
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if(errMessage!=null){
                    ControlUtils.showToast(context, "查询出错，请重试!", Gravity.CENTER, Toast.LENGTH_SHORT);
                    return;
                }
                if(goodsList == null || goodsList.size()<=0){
                    ControlUtils.showToast(context,"无该品牌的商品!", Gravity.CENTER,Toast.LENGTH_SHORT);
                    return;
                }
                handler.obtainMessage(MSG_REFRESH_LISTVIEW,goodsList).sendToTarget();
            }
        }.execute();
    }

    /**
     * 执行按关键字查询商品的操作
     * @param context
     * @param dbUtils
     * @param keyword  关键字
     */
    public void executeFindAllGoodsByKeyword(final Context context,final DbUtils dbUtils,final String keyword){
        new AsyncTask<Void,Void,Void>(){

            private ProgressDialog dialog = null;
            private String errMessage = null;
            private List<HashMap<String,Object>> goodsList = null;//商品集合

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在加载中...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try{
                    goodsList = FfindGoodsDbHelper.findAllCxqhGoodsByKeyword(dbUtils,keyword);
                }catch (Exception e){
                    e.printStackTrace();
                    errMessage = e.getMessage();
                    System.out.println("----->按商品品牌查询出错："+errMessage);
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if(errMessage!=null){
                    ControlUtils.showToast(context,"查询出错，请重试!", Gravity.CENTER,Toast.LENGTH_SHORT);
                    return;
                }
                if(goodsList == null || goodsList.size()<=0){
                    ControlUtils.showToast(context, "无该品牌的商品!", Gravity.CENTER, Toast.LENGTH_SHORT);
                    return;
                }
                handler.obtainMessage(MSG_REFRESH_LISTVIEW,goodsList).sendToTarget();
            }
        }.execute();
    }

    /**
     * 页面返回
     */
    public void goBack() {
        this.setResult(Activity.RESULT_OK);
        this.finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    @OnClick(value = {R.id.pcxqhFind_imgBack})
    public void OnBackClick(View view) {
        goBack();//页面返回
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();//页面返回
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 请求商品库存数据
     */
    public void requestGoodsStockInfo(final Context context,final DbUtils dbUtils){
        if(!NetworkUtils.isNetAvailable(context)){
            ControlUtils.showToast(context,"当前网络不可用，请检查您的网络是否正常!", Gravity.CENTER,Toast.LENGTH_SHORT);
            return;
        }
        new AsyncTask<Void,Void,Void>(){
            private String errMessage;
            private ProgressDialog dialog;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在下载库存信息...");
                imgRefresh.startAnimation(getRefreshAnimation());
            }
            @Override
            protected Void doInBackground(Void... pram) {
                try{
                    RequestParams params = new RequestParams("UTF-8");
                    String methodName = "Cx_MrMdKc";
                    String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\"}";
                    System.out.println("-----> 获取商品库存数据：" + messageBody);
                    params.addBodyParameter("Method", methodName);
                    params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
                    params.addBodyParameter("MessageBody", messageBody);
                    InputStream inputStream = new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT)
                            .configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT)
                            .sendSync(HttpRequest.HttpMethod.POST, SystemData.BASE_URL, params);
                    if(inputStream!=null){
                        String result = FileUtils.stream2string(inputStream,"UTF-8");
                        BaseResultModel resultModel = new Gson().fromJson(result, BaseResultModel.class);
                        if (resultModel != null && resultModel.Result.equals("0000")) {
                            try{
                                List<CxqhTable> cxqhTables = new Gson().fromJson(resultModel.Data,new TypeToken<List<CxqhTable>>(){}.getType());
                                if(cxqhTables!=null && cxqhTables.size()>0) {
                                    if(dbUtils.tableIsExist(CxqhTable.class)){//如果数据表存，则删除所有数据
                                        dbUtils.deleteAll(CxqhTable.class);
                                    }
                                    dbUtils.saveAll(cxqhTables);//存储下载下来的商品库存数据
                                    return null;
                                }
                            }catch (Exception e){
                                errMessage = e.getMessage();
                                e.printStackTrace();
                            }
                        } else {
                            errMessage = "获取商品库存异常，请重试!";
                            System.out.println("------>请求商品库存异常!");
                        }
                    }
                }catch (Exception e){
                    errMessage = e.getMessage();
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if (dialog != null && dialog.isShowing()) dialog.dismiss();
                imgRefresh.clearAnimation();//停止刷新按钮旋转
                if(errMessage==null) {
                    ControlUtils.showToast(context, "商品库存更新完成!", Gravity.CENTER, Toast.LENGTH_SHORT);
                    return;
                }
                ControlUtils.showToast(context, "商品库存更新异常，请重试!", Gravity.CENTER, Toast.LENGTH_SHORT);
            }
        }.execute();

    }

}
